__author__ = 'alex'
# -*- coding: utf-8 -*-

#import MySQLdb
import MySQLdb
from attribtranslator import *
from dictclient import enquote


RU = u"ru"
EN = u"en"
ERROR_DUPLICATE_ENTRY = 1062

"""
DB_PREFIX = "ru_"
TABLE_PAGE = DB_PREFIX + "page"
TABLE_CATEGORYLINKS = DB_PREFIX + "categorylinks"
TABLE_INFOBOX = DB_PREFIX + "infobox"
TABLE_INFOBOX_CATEGORIES = DB_PREFIX + "infobox_categories"
TABLE_INFOBOX_ATTRIBUTES = DB_PREFIX + "infobox_attrib"

"""


'''
def write_translation(conn, en_id, ru_id):
    values = [en_id, ru_id]
    cursor = conn.cursor()
    try:
        write_to_db(cursor, 'inf_atr_translation')
    cursor.close()
'''

def write_to_db(cursor, table_name, columns, values):
    query = "INSERT INTO " + table_name + \
				"(" + ", ".join(columns) + ")" \
				" VALUES ( " +  ", ".join(values) + " )"
    try:
        cursor.execute(query)
    except MySQLdb.Error, e:
        #it`s OK if duplicate
        if e.args[0] == ERROR_DUPLICATE_ENTRY:
            return

        #show some error environment
        print "EXCEPTION in write_to_db"
        print "values = ", values
        #delete unnecessary spaces for pretty report
        query = ' '.join(query.split())
        print "query = ", query
        raise



def execute(conn, query):
    try:
        cursor = conn.cursor()
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        return result
    except Exception, e:
        print "exception in execute function on:"
        print "query =", query
        raise

def get_attrib(conn, prefix, id):
    query = u"SELECT ia_id, ia_name FROM " + prefix + "_infobox_attrib" + \
        u" WHERE ia_of = " + id

    return [(unicode(str(a[0]), "utf-8"), unicode(a[1], "utf-8")) for a in execute(conn, query)]


def get_attrib_list(translator, en_atr):
    en_atr_list = []

    for a in en_atr:
        #make 5 attempts before giving up
        attempts = 0
        while attempts < 5:
            attempts += 1
            try:
                en_atr_list.append(Attribute(a, translator))
                break
            except Exception, e:
                #print "cant translate atr: ", a[0], a[1]
                translator = Translator()
        if attempts == 5:
            print "cant translate atr: ", a[0], a[1]

    return en_atr_list


query = u"SELECT itt_ru, itt_en from inf_title_translation"

conn = MySQLdb.connect (host = "localhost",	user = "alex", db = "ruwiki")
conn.set_character_set('utf8')


title_translation = execute(conn, query)
'''
c = 0
for t in title_translation:
    if t[0] == 234635:
        print c, t[0], t[1]
    c += 1
'''

cursor = conn.cursor()
t = Translator()
columns = ['iat_en', 'iat_ru']

for tt in title_translation:
    ru_atr = get_attrib(conn, RU, str(tt[0]))
    en_atr = get_attrib(conn, EN, str(tt[1]))
    #en_atr_list = [ Attribute(a, t) for a in en_atr]
    en_atr_list = get_attrib_list(t, en_atr)
    for ra in ru_atr:
        for ea in en_atr_list:
            if ea.isTranslation(ra[1]):
                write_to_db(cursor, 'inf_atr_translation', columns, [ra[0], ea.id])
    conn.commit()

cursor.close()



'''
n = 460

ru_atr = get_attrib(conn, RU, str(title_translation[n][0]))
en_atr = get_attrib(conn, EN, str(title_translation[n][1]))

print "RU:"

for a in ru_atr:
    print a[1]

print ""

print "EN:"
for a in en_atr:
    print a[1]



en_atr_list = [ Attribute(a, t) for a in en_atr]
#print en_atr_list

for ra in ru_atr:
    for ea in en_atr_list:
        if ea.isTranslation(ra[1]):
            print ra[1], ea.sourceString

'''



  